<template>
  <div class="checkout-container">
    <h2>订单结算</h2>
    <div v-if="cart.length === 0">购物车为空</div>
    <div v-else>
      <div v-for="item in cart" :key="item.id" class="checkout-item">
        <h3>{{ item.name }}</h3>
        <p>数量：{{ item.quantity }}</p>
        <p>价格：¥{{ item.price }}</p>
      </div>
      <div class="checkout-total">总价：¥{{ totalPrice }}</div>
      <button @click="submitOrder" :disabled="loading">提交订单</button>
      <div v-if="success" class="success">{{ success }}</div>
      <div v-if="error" class="error">{{ error }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import axios from '../api/axios';
import { useRouter } from 'vue-router';

const cart = ref<any[]>(JSON.parse(localStorage.getItem('cart') || '[]'));
const totalPrice = computed(() => cart.value.reduce((sum, item) => sum + item.price * item.quantity, 0));
const loading = ref(false);
const success = ref('');
const error = ref('');
const router = useRouter();

const submitOrder = async () => {
  loading.value = true;
  error.value = '';
  success.value = '';
  try {
    // 假设后端 /order 支持批量下单
    const res = await axios.post('/order', {
      items: cart.value.map(item => ({ teaId: item.id, quantity: item.quantity })),
      totalPrice: totalPrice.value,
    });
    success.value = '下单成功！';
    localStorage.removeItem('cart');
    setTimeout(() => router.push('/orders'), 1500);
  } catch (e: any) {
    error.value = e.response?.data || '下单失败';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.checkout-container {
  max-width: 600px;
  margin: 40px auto;
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px #eee;
}
.checkout-item {
  border-bottom: 1px solid #eee;
  padding: 16px 0;
}
.checkout-total {
  font-weight: bold;
  margin: 16px 0;
}
.success {
  color: green;
  margin-top: 8px;
}
.error {
  color: red;
  margin-top: 8px;
}
</style>
